<?php
/**
 *
 *
 */
class UserController extends AppController
{
    public $name       = "User";
    public $uses       = array('User', 'Privilege', 'RestrictionGrant', 'SmtpSetting');
    public $components = array('MyEmail');


    public function login()
    {        
        $this->theme = "admin";
        $msg = "";

        if ($this->data['login']) {
            if ($this->data['login']['username'] && $this->data['login']['password']) {
                $data['uname'] = $this->data['login']['username'];
                $data['token'] = sha1($this->data['login']['password']);
                $validate = $this->Authenticate->validateToken($data);
                if ($validate) {
                    self::redirect('/ticket/ticketmgnt');
                }
            } else {
                $msg = "Please input your username and password";
            }
        }

        self::set('msg', $msg);
    }

    public function logout()
    {
        $this->Authenticate->logout();
    }

    public function usermgnt()
    {
        $this->Authenticate->checkMyLogin(13);
        $this->theme = "admin";
        $error = null;

        // process form request
        if ($this->data['flag']) {
            switch($this->data['flag']){
                case "delete":
                    $this->Authenticate->checkMyLogin(12);
                    foreach($this->data['row']['id'] as $id){
                        $result = $this->User->_save(array('active' => 0), $id);
                        if (is_string($result)) {
                            $error[] = $result;
                        }

                        if (is_numeric($result)) {
                            $error = "deleted";
                        }
                    }
                    break;
            } // switch
        }

        $limit = isset($this->data['limit'])?$this->data['limit']:20;
        $this->paginate['conditions'][] = array('User.active' => 1);
        $this->paginate['limit'] = $limit;
        $this->paginate['order'] = array('User.privilegeId' => 'ASC');
        $data = $this->paginate('User');

        self::set('limit', $limit);
        self::set('users', $data);
        self::set('cnt', count($data));
        self::set('error', $error);
    }

    public function userdetails($uid = 0)
    {
        $this->theme = "admin";
        $alert = null;
        $msg = null;
        $update = null;


        // check if action is for update
        if ($uid > 0) {
            $this->Authenticate->checkMyLogin(11);
            $user_details = $this->User->get_user_info('first', array('userId' => $uid), array('*'));
            if ($user_details) {
                $update['lname'] = $user_details['User']['lname'];
                $update['fname'] = $user_details['User']['fname'];
                $update['uname'] = $user_details['User']['uname'];
                $update['privilegeId'] = $user_details['User']['privilegeId'];
                $update['email_address'] = $user_details['User']['email_address'];
            }
        } else {
            $this->Authenticate->checkMyLogin(10);
        }

        if ($this->data['user_details']) {
            $success = self::create_user($this->data['user_details'], $uid);
            if (is_numeric($success)) {
                if ($uid == 0) {
                    $msg[] = "You have successfully added new user";
                } else {
                    $msg[] = "You have successfully updated selected user";
                }

            } else {
                if ($success == "existing") {
                    $alert = "User is already existing in database";
                } else {
                    $alert = $success;

                }

                $msg = null;
            }
        }

        $privileges = $this->Privilege->MyGenerateList("active=1", null, null, "{n}.Privilege.privilegeId", "{n}.Privilege.name");
        self::set('privileges', $privileges);
        self::set('update', $update);
        self::set('uid', $uid);
        self::set('error', $alert);
        self::set('msg', $msg);
        self::set('page_title', ($uid == 0)?'Add User Details':"Edit User Details");
    }

    public function deny()
    {
        $this->theme = "admin";       
    }




    /**
     * protected methods
     */
    protected function create_user($data, $uid = 0)
    {
        // bypass this check if request is for update
        if ($uid == 0) {
            $conditions = array(
                'lname' => $data['lname'],
                'fname' => $data['fname'],
                'uname LIKE' => '%'.$data['uname'].'%',
                'email_address LIKE' => '%'.$data['email_address'].'%'
            );
            $fields = array('userId');
            $unique = $this->User->get_user_info('first', $conditions, $fields);
        } else {
            $unique = null;
        }

        if ($unique) {
            return "existing";
        } else {
            $data['active'] = 1;
            $data['date_added'] = date('Y-m-d H:i:s');
            $data['token'] = self::hashpassword($data['token']);

            // ignore, if for update and token is empty
            if ($uid == 0 && empty($data['token'])) unset($data['token']);

            return $this->User->_save($data, $uid);
        }
    }

    protected function hashpassword($token)
    {
        return sha1($token);
    }

}
?>